home *** CD-ROM | disk | FTP | other *** search
/ SGI Freeware 1999 August / SGI Freeware 1999 August.iso / dist / fw_perl.idb / usr / freeware / catman / u_man / cat1 / perlxstut.Z / perlxstut
Encoding:
Text File  |  1998-10-28  |  36.5 KB  |  1,123 lines

  1.  
  2.  
  3.  
  4.      PPPPEEEERRRRLLLLXXXXSSSSTTTTUUUUTTTT((((1111))))    22223333////JJJJuuuullll////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))      PPPPEEEERRRRLLLLXXXXSSSSTTTTUUUUTTTT((((1111))))
  5.  
  6.  
  7.  
  8.      NNNNAAAAMMMMEEEE
  9.       perlXStut - Tutorial for XSUBs
  10.  
  11.      DDDDEEEESSSSCCCCRRRRIIIIPPPPTTTTIIIIOOOONNNN
  12.       This tutorial    will educate the reader    on the steps involved
  13.       in creating a    Perl extension.     The reader is assumed to have
  14.       access to the    _p_e_r_l_g_u_t_s manpage and the _p_e_r_l_x_s    manpage.
  15.  
  16.       This tutorial    starts with very simple    examples and becomes
  17.       more complex,    with each new example adding new features.
  18.       Certain concepts may not be completely explained until later
  19.       in the tutorial to ease the reader slowly into building
  20.       extensions.
  21.  
  22.       VVVVEEEERRRRSSSSIIIIOOOONNNN CCCCAAAAVVVVEEEEAAAATTTT
  23.  
  24.       This tutorial    tries hard to keep up with the latest
  25.       development versions of Perl.     This often means that it is
  26.       sometimes in advance of the latest released version of Perl,
  27.       and that certain features described here might not work on
  28.       earlier versions.  This section will keep track of when
  29.       various features were    added to Perl 5.
  30.  
  31.       +o   In versions of Perl 5.002    prior to the gamma version,
  32.           the test script in Example 1 will    not function properly.
  33.           You need to change the "use lib" line to read:
  34.  
  35.               use lib './blib';
  36.  
  37.  
  38.       +o   In versions of Perl 5.002    prior to version beta 3, the
  39.           line in the .xs file about "PROTOTYPES: DISABLE" will
  40.           cause a compiler error.  Simply remove that line from
  41.           the file.
  42.  
  43.       +o   In versions of Perl 5.002    prior to version 5.002b1h, the
  44.           test.pl file was not automatically created by h2xs.
  45.           This means that you cannot say "make test" to run    the
  46.           test script.  You    will need to add the following line
  47.           before the "use extension" statement:
  48.  
  49.               use lib './blib';
  50.  
  51.  
  52.       +o   In versions 5.000    and 5.001, instead of using the    above
  53.           line, you    will need to use the following line:
  54.  
  55.               BEGIN { unshift(@INC, "./blib") }
  56.  
  57.  
  58.       +o   This document assumes that the executable    named "perl"
  59.           is Perl version 5.  Some systems may have    installed Perl
  60.  
  61.  
  62.  
  63.      Page 1                        (printed 10/23/98)
  64.  
  65.  
  66.  
  67.  
  68.  
  69.  
  70.      PPPPEEEERRRRLLLLXXXXSSSSTTTTUUUUTTTT((((1111))))    22223333////JJJJuuuullll////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))      PPPPEEEERRRRLLLLXXXXSSSSTTTTUUUUTTTT((((1111))))
  71.  
  72.  
  73.  
  74.           version 5    as "perl5".
  75.  
  76.       DDDDYYYYNNNNAAAAMMMMIIIICCCC VVVVEEEERRRRSSSSUUUUSSSS SSSSTTTTAAAATTTTIIIICCCC
  77.  
  78.       It is    commonly thought that if a system does not have    the
  79.       capability to    load a library dynamically, you    cannot build
  80.       XSUBs.  This is incorrect.  You _c_a_n build them, but you must
  81.       link the XSUB's subroutines with the rest of Perl, creating
  82.       a new    executable.  This situation is similar to Perl 4.
  83.  
  84.       This tutorial    can still be used on such a system.  The XSUB
  85.       build    mechanism will check the system    and build a
  86.       dynamically-loadable library if possible, or else a static
  87.       library and then, optionally,    a new statically-linked
  88.       executable with that static library linked in.
  89.  
  90.       Should you wish to build a statically-linked executable on a
  91.       system which can dynamically load libraries, you may,    in all
  92.       the following    examples, where    the command "make" with    no
  93.       arguments is executed, run the command "make perl" instead.
  94.  
  95.       If you have generated    such a statically-linked executable by
  96.       choice, then instead of saying "make test", you should say
  97.       "make    test_static".  On systems that cannot build
  98.       dynamically-loadable libraries at all, simply    saying "make
  99.       test"    is sufficient.
  100.  
  101.       EEEEXXXXAAAAMMMMPPPPLLLLEEEE 1111
  102.  
  103.       Our first extension will be very simple.  When we call the
  104.       routine in the extension, it will print out a    well-known
  105.       message and return.
  106.  
  107.       Run h2xs -A -n Mytest.  This creates a directory named
  108.       Mytest, possibly under ext/ if that directory    exists in the
  109.       current working directory.  Several files will be created in
  110.       the Mytest dir, including MANIFEST, Makefile.PL, Mytest.pm,
  111.       Mytest.xs, test.pl, and Changes.
  112.  
  113.       The MANIFEST file contains the names of all the files
  114.       created.
  115.  
  116.       The file Makefile.PL should look something like this:
  117.  
  118.  
  119.  
  120.  
  121.  
  122.  
  123.  
  124.  
  125.  
  126.  
  127.  
  128.  
  129.      Page 2                        (printed 10/23/98)
  130.  
  131.  
  132.  
  133.  
  134.  
  135.  
  136.      PPPPEEEERRRRLLLLXXXXSSSSTTTTUUUUTTTT((((1111))))    22223333////JJJJuuuullll////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))      PPPPEEEERRRRLLLLXXXXSSSSTTTTUUUUTTTT((((1111))))
  137.  
  138.  
  139.  
  140.           use ExtUtils::MakeMaker;
  141.           # See    lib/ExtUtils/MakeMaker.pm for details of how to    influence
  142.           # the    contents of the    Makefile that is written.
  143.           WriteMakefile(
  144.               'NAME'      => 'Mytest',
  145.               'VERSION_FROM' =>    'Mytest.pm', # finds $VERSION
  146.               'LIBS'      => [''],   # e.g., '-lm'
  147.               'DEFINE'      => '',     # e.g., '-DHAVE_SOMETHING'
  148.               'INC'      => '',     # e.g., '-I/usr/include/other'
  149.           );
  150.  
  151.       The file Mytest.pm should start with something like this:
  152.  
  153.           package Mytest;
  154.  
  155.           require Exporter;
  156.           require DynaLoader;
  157.  
  158.           @ISA = qw(Exporter DynaLoader);
  159.           # Items to export into callers namespace by default. Note: do    not export
  160.           # names by default without a very good reason. Use EXPORT_OK instead.
  161.           # Do not simply export all your public functions/methods/constants.
  162.           @EXPORT = qw(
  163.  
  164.           );
  165.           $VERSION = '0.01';
  166.  
  167.           bootstrap Mytest $VERSION;
  168.  
  169.           # Preloaded methods go here.
  170.  
  171.           # Autoload methods go    after __END__, and are processed by the    autosplit program.
  172.  
  173.           1;
  174.           __END__
  175.           # Below is the stub of documentation for your    module.    You better edit    it!
  176.  
  177.       And the Mytest.xs file should    look something like this:
  178.  
  179.           #ifdef __cplusplus
  180.           extern "C" {
  181.           #endif
  182.           #include "EXTERN.h"
  183.           #include "perl.h"
  184.           #include "XSUB.h"
  185.           #ifdef __cplusplus
  186.           }
  187.           #endif
  188.  
  189.           PROTOTYPES: DISABLE
  190.  
  191.           MODULE = Mytest      PACKAGE = Mytest
  192.  
  193.  
  194.  
  195.      Page 3                        (printed 10/23/98)
  196.  
  197.  
  198.  
  199.  
  200.  
  201.  
  202.      PPPPEEEERRRRLLLLXXXXSSSSTTTTUUUUTTTT((((1111))))    22223333////JJJJuuuullll////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))      PPPPEEEERRRRLLLLXXXXSSSSTTTTUUUUTTTT((((1111))))
  203.  
  204.  
  205.  
  206.       Let's    edit the .xs file by adding this to the    end of the
  207.       file:
  208.  
  209.           void
  210.           hello()
  211.               CODE:
  212.               printf("Hello, world!\n");
  213.  
  214.       Now we'll run    "perl Makefile.PL".  This will create a    real
  215.       Makefile, which make needs.  Its output looks    something
  216.       like:
  217.  
  218.           % perl Makefile.PL
  219.           Checking if your kit is complete...
  220.           Looks    good
  221.           Writing Makefile for Mytest
  222.           %
  223.  
  224.       Now, running make will produce output    that looks something
  225.       like this (some long lines shortened for clarity):
  226.  
  227.           % make
  228.           umask    0 && cp    Mytest.pm ./blib/Mytest.pm
  229.           perl xsubpp -typemap typemap Mytest.xs >Mytest.tc && mv Mytest.tc Mytest.c
  230.           cc -c    Mytest.c
  231.           Running Mkbootstrap for Mytest ()
  232.           chmod    644 Mytest.bs
  233.           LD_RUN_PATH="" ld -o ./blib/PA-RISC1.1/auto/Mytest/Mytest.sl -b Mytest.o
  234.           chmod    755 ./blib/PA-RISC1.1/auto/Mytest/Mytest.sl
  235.           cp Mytest.bs ./blib/PA-RISC1.1/auto/Mytest/Mytest.bs
  236.           chmod    644 ./blib/PA-RISC1.1/auto/Mytest/Mytest.bs
  237.  
  238.       Now, although    there is already a test.pl template ready for
  239.       us, for this example only, we'll create a special test
  240.       script.  Create a file called    hello that looks like this:
  241.  
  242.           #! /opt/perl5/bin/perl
  243.  
  244.           use ExtUtils::testlib;
  245.  
  246.           use Mytest;
  247.  
  248.           Mytest::hello();
  249.  
  250.       Now we run the script    and we should see the following
  251.       output:
  252.  
  253.           % perl hello
  254.           Hello, world!
  255.           %
  256.  
  257.  
  258.  
  259.  
  260.  
  261.      Page 4                        (printed 10/23/98)
  262.  
  263.  
  264.  
  265.  
  266.  
  267.  
  268.      PPPPEEEERRRRLLLLXXXXSSSSTTTTUUUUTTTT((((1111))))    22223333////JJJJuuuullll////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))      PPPPEEEERRRRLLLLXXXXSSSSTTTTUUUUTTTT((((1111))))
  269.  
  270.  
  271.  
  272.       EEEEXXXXAAAAMMMMPPPPLLLLEEEE 2222
  273.  
  274.       Now let's add    to our extension a subroutine that will    take a
  275.       single argument and return 1 if the argument is even,    0 if
  276.       the argument is odd.
  277.  
  278.       Add the following to the end of Mytest.xs:
  279.  
  280.           int
  281.           is_even(input)
  282.               int      input
  283.               CODE:
  284.               RETVAL = (input % 2 == 0);
  285.               OUTPUT:
  286.               RETVAL
  287.  
  288.       There    does not need to be white space    at the start of    the
  289.       "int input" line, but    it is useful for improving
  290.       readability.    The semi-colon at the end of that line is also
  291.       optional.
  292.  
  293.       Any white space may be between the "int" and "input".     It is
  294.       also okay for    the four lines starting    at the "CODE:" line to
  295.       not be indented.  However, for readability purposes, it is
  296.       suggested that you indent them 8 spaces (or one normal tab
  297.       stop).
  298.  
  299.       Now rerun make to rebuild our    new shared library.
  300.  
  301.       Now perform the same steps as    before,    generating a Makefile
  302.       from the Makefile.PL file, and running make.
  303.  
  304.       To test that our extension works, we now need    to look    at the
  305.       file test.pl.     This file is set up to    imitate    the same kind
  306.       of testing structure that Perl itself    has.  Within the test
  307.       script, you perform a    number of tests    to confirm the
  308.       behavior of the extension, printing "ok" when    the test is
  309.       correct, "not    ok" when it is not.  Change the    print
  310.       statement in the BEGIN block to print    "1..4",    and add    the
  311.       following code to the    end of the file:
  312.  
  313.           print    &Mytest::is_even(0) == 1 ? "ok 2" : "not ok 2",    "\n";
  314.           print    &Mytest::is_even(1) == 0 ? "ok 3" : "not ok 3",    "\n";
  315.           print    &Mytest::is_even(2) == 1 ? "ok 4" : "not ok 4",    "\n";
  316.  
  317.       We will be calling the test script through the command "make
  318.       test".  You should see output    that looks something like
  319.       this:
  320.  
  321.  
  322.  
  323.  
  324.  
  325.  
  326.  
  327.      Page 5                        (printed 10/23/98)
  328.  
  329.  
  330.  
  331.  
  332.  
  333.  
  334.      PPPPEEEERRRRLLLLXXXXSSSSTTTTUUUUTTTT((((1111))))    22223333////JJJJuuuullll////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))      PPPPEEEERRRRLLLLXXXXSSSSTTTTUUUUTTTT((((1111))))
  335.  
  336.  
  337.  
  338.           % make test
  339.           PERL_DL_NONLAZY=1 /opt/perl5.002b2/bin/perl (lots of -I arguments) test.pl
  340.           1..4
  341.           ok 1
  342.           ok 2
  343.           ok 3
  344.           ok 4
  345.           %
  346.  
  347.  
  348.       WWWWHHHHAAAATTTT HHHHAAAASSSS GGGGOOOONNNNEEEE    OOOONNNN????
  349.  
  350.       The program h2xs is the starting point for creating
  351.       extensions.  In later    examples we'll see how we can use h2xs
  352.       to read header files and generate templates to connect to C
  353.       routines.
  354.  
  355.       h2xs creates a number    of files in the    extension directory.
  356.       The file Makefile.PL is a perl script    which will generate a
  357.       true Makefile    to build the extension.     We'll take a closer
  358.       look at it later.
  359.  
  360.       The files <extension>.pm and <extension>.xs contain the meat
  361.       of the extension.  The .xs file holds    the C routines that
  362.       make up the extension.  The .pm file contains    routines that
  363.       tell Perl how    to load    your extension.
  364.  
  365.       Generating and invoking the Makefile created a directory
  366.       blib (which stands for "build    library") in the current
  367.       working directory.  This directory will contain the shared
  368.       library that we will build.  Once we have tested it, we can
  369.       install it into its final location.
  370.  
  371.       Invoking the test script via "make test" did something very
  372.       important.  It invoked perl with all those -I    arguments so
  373.       that it could    find the various files that are    part of    the
  374.       extension.
  375.  
  376.       It is    _v_e_r_y important that while you are still    testing
  377.       extensions that you use "make    test".    If you try to run the
  378.       test script all by itself, you will get a fatal error.
  379.  
  380.       Another reason it is important to use    "make test" to run
  381.       your test script is that if you are testing an upgrade to an
  382.       already-existing version, using "make    test" insures that you
  383.       use your new extension, not the already-existing version.
  384.  
  385.       When Perl sees a use extension;, it searches for a file with
  386.       the same name    as the use'd extension that has    a .pm suffix.
  387.       If that file cannot be found,    Perl dies with a fatal error.
  388.       The default search path is contained in the @INC array.
  389.  
  390.  
  391.  
  392.  
  393.      Page 6                        (printed 10/23/98)
  394.  
  395.  
  396.  
  397.  
  398.  
  399.  
  400.      PPPPEEEERRRRLLLLXXXXSSSSTTTTUUUUTTTT((((1111))))    22223333////JJJJuuuullll////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))      PPPPEEEERRRRLLLLXXXXSSSSTTTTUUUUTTTT((((1111))))
  401.  
  402.  
  403.  
  404.       In our case, Mytest.pm tells perl that it will need the
  405.       Exporter and Dynamic Loader extensions.  It then sets    the
  406.       @ISA and @EXPORT arrays and the $VERSION scalar; finally it
  407.       tells    perl to    bootstrap the module.  Perl will call its
  408.       dynamic loader routine (if there is one) and load the    shared
  409.       library.
  410.  
  411.       The two arrays that are set in the .pm file are very
  412.       important.  The @ISA array contains a    list of    other packages
  413.       in which to search for methods (or subroutines) that do not
  414.       exist    in the current package.     The @EXPORT array tells Perl
  415.       which    of the extension's routines should be placed into the
  416.       calling package's namespace.
  417.  
  418.       It's important to select what    to export carefully.  Do NOT
  419.       export method    names and do NOT export    anything else _b_y
  420.       _d_e_f_a_u_l_t without a good reason.
  421.  
  422.       As a general rule, if    the module is trying to    be object-
  423.       oriented then    don't export anything.    If it's    just a
  424.       collection of    functions then you can export any of the
  425.       functions via    another    array, called @EXPORT_OK.
  426.  
  427.       See the _p_e_r_l_m_o_d manpage for more information.
  428.  
  429.       The $VERSION variable    is used    to ensure that the .pm file
  430.       and the shared library are "in sync" with each other.     Any
  431.       time you make    changes    to the .pm or .xs files, you should
  432.       increment the    value of this variable.
  433.  
  434.       WWWWRRRRIIIITTTTIIIINNNNGGGG GGGGOOOOOOOODDDD TTTTEEEESSSSTTTT SSSSCCCCRRRRIIIIPPPPTTTTSSSS
  435.  
  436.       The importance of writing good test scripts cannot be
  437.       overemphasized.  You should closely follow the "ok/not ok"
  438.       style    that Perl itself uses, so that it is very easy and
  439.       unambiguous to determine the outcome of each test case.
  440.       When you find    and fix    a bug, make sure you add a test    case
  441.       for it.
  442.  
  443.       By running "make test", you ensure that your test.pl script
  444.       runs and uses    the correct version of your extension.    If you
  445.       have many test cases,    you might want to copy Perl's test
  446.       style.  Create a directory named "t",    and ensure all your
  447.       test files end with the suffix ".t".    The Makefile will
  448.       properly run all these test files.
  449.  
  450.       EEEEXXXXAAAAMMMMPPPPLLLLEEEE 3333
  451.  
  452.       Our third extension will take    one argument as    its input,
  453.       round    off that value,    and set    the _a_r_g_u_m_e_n_t to    the rounded
  454.       value.
  455.  
  456.  
  457.  
  458.  
  459.      Page 7                        (printed 10/23/98)
  460.  
  461.  
  462.  
  463.  
  464.  
  465.  
  466.      PPPPEEEERRRRLLLLXXXXSSSSTTTTUUUUTTTT((((1111))))    22223333////JJJJuuuullll////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))      PPPPEEEERRRRLLLLXXXXSSSSTTTTUUUUTTTT((((1111))))
  467.  
  468.  
  469.  
  470.       Add the following to the end of Mytest.xs:
  471.  
  472.           void
  473.           round(arg)
  474.               double  arg
  475.               CODE:
  476.               if (arg > 0.0) {
  477.                   arg =    floor(arg + 0.5);
  478.               } else if (arg < 0.0)    {
  479.                   arg =    ceil(arg - 0.5);
  480.               } else {
  481.                   arg =    0.0;
  482.               }
  483.               OUTPUT:
  484.               arg
  485.  
  486.       Edit the Makefile.PL file so that the    corresponding line
  487.       looks    like this:
  488.  
  489.           'LIBS'      => ['-lm'],   # e.g., '-lm'
  490.  
  491.       Generate the Makefile    and run    make.  Change the BEGIN    block
  492.       to print out "1..9" and add the following to test.pl:
  493.  
  494.           $i = -1.5; &Mytest::round($i); print $i == -2.0 ? "ok    5" : "not ok 5", "\n";
  495.           $i = -1.1; &Mytest::round($i); print $i == -1.0 ? "ok    6" : "not ok 6", "\n";
  496.           $i = 0.0; &Mytest::round($i);    print $i == 0.0    ? "ok 7" : "not    ok 7", "\n";
  497.           $i = 0.5; &Mytest::round($i);    print $i == 1.0    ? "ok 8" : "not    ok 8", "\n";
  498.           $i = 1.2; &Mytest::round($i);    print $i == 1.0    ? "ok 9" : "not    ok 9", "\n";
  499.  
  500.       Running "make    test" should now print out that    all nine tests
  501.       are okay.
  502.  
  503.       You might be wondering if you    can round a constant.  To see
  504.       what happens,    add the    following line to test.pl temporarily:
  505.  
  506.           &Mytest::round(3);
  507.  
  508.       Run "make test" and notice that Perl dies with a fatal
  509.       error.  Perl won't let you change the    value of constants!
  510.  
  511.       WWWWHHHHAAAATTTT''''SSSS NNNNEEEEWWWW HHHHEEEERRRREEEE????
  512.  
  513.       Two things are new here.  First, we've made some changes to
  514.       Makefile.PL.    In this    case, we've specified an extra library
  515.       to link in, the math library libm.  We'll talk later about
  516.       how to write XSUBs that can call every routine in a library.
  517.  
  518.       Second, the value of the function is being passed back not
  519.       as the function's return value, but through the same
  520.       variable that    was passed into    the function.
  521.  
  522.  
  523.  
  524.  
  525.      Page 8                        (printed 10/23/98)
  526.  
  527.  
  528.  
  529.  
  530.  
  531.  
  532.      PPPPEEEERRRRLLLLXXXXSSSSTTTTUUUUTTTT((((1111))))    22223333////JJJJuuuullll////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))      PPPPEEEERRRRLLLLXXXXSSSSTTTTUUUUTTTT((((1111))))
  533.  
  534.  
  535.  
  536.       IIIINNNNPPPPUUUUTTTT    AAAANNNNDDDD OOOOUUUUTTTTPPPPUUUUTTTT PPPPAAAARRRRAAAAMMMMEEEETTTTEEEERRRRSSSS
  537.  
  538.       You specify the parameters that will be passed into the XSUB
  539.       just after you declare the function return value and name.
  540.       Each parameter line starts with optional white space,    and
  541.       may have an optional terminating semicolon.
  542.  
  543.       The list of output parameters    occurs after the OUTPUT:
  544.       directive.  The use of RETVAL    tells Perl that    you wish to
  545.       send this value back as the return value of the XSUB
  546.       function.  In    Example    3, the value we    wanted returned    was
  547.       contained in the same    variable we passed in, so we listed it
  548.       (and not RETVAL) in the OUTPUT: section.
  549.  
  550.       TTTTHHHHEEEE XXXXSSSSUUUUBBBBPPPPPPPP CCCCOOOOMMMMPPPPIIIILLLLEEEERRRR
  551.  
  552.       The compiler xsubpp takes the    XS code    in the .xs file    and
  553.       converts it into C code, placing it in a file    whose suffix
  554.       is .c.  The C    code created makes heavy use of    the C
  555.       functions within Perl.
  556.  
  557.       TTTTHHHHEEEE TTTTYYYYPPPPEEEEMMMMAAAAPPPP FFFFIIIILLLLEEEE
  558.  
  559.       The xsubpp compiler uses rules to convert from Perl's    data
  560.       types    (scalar, array,    etc.) to C's data types    (int, char *,
  561.       etc.).  These    rules are stored in the    typemap    file
  562.       ($PERLLIB/ExtUtils/typemap).    This file is split into    three
  563.       parts.
  564.  
  565.       The first part attempts to map various C data    types to a
  566.       coded    flag, which has    some correspondence with the various
  567.       Perl types.  The second part contains    C code which xsubpp
  568.       uses for input parameters.  The third    part contains C    code
  569.       which    xsubpp uses for    output parameters.  We'll talk more
  570.       about    the C code later.
  571.  
  572.       Let's    now take a look    at a portion of    the .c file created
  573.       for our extension.
  574.  
  575.  
  576.  
  577.  
  578.  
  579.  
  580.  
  581.  
  582.  
  583.  
  584.  
  585.  
  586.  
  587.  
  588.  
  589.  
  590.  
  591.      Page 9                        (printed 10/23/98)
  592.  
  593.  
  594.  
  595.  
  596.  
  597.  
  598.      PPPPEEEERRRRLLLLXXXXSSSSTTTTUUUUTTTT((((1111))))    22223333////JJJJuuuullll////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))      PPPPEEEERRRRLLLLXXXXSSSSTTTTUUUUTTTT((((1111))))
  599.  
  600.  
  601.  
  602.           XS(XS_Mytest_round)
  603.           {
  604.               dXSARGS;
  605.               if (items    != 1)
  606.               croak("Usage:    Mytest::round(arg)");
  607.               {
  608.               double  arg =    (double)SvNV(ST(0));      /* XXXXX */
  609.               if (arg > 0.0) {
  610.                   arg =    floor(arg + 0.5);
  611.               } else if (arg < 0.0)    {
  612.                   arg =    ceil(arg - 0.5);
  613.               } else {
  614.                   arg =    0.0;
  615.               }
  616.               sv_setnv(ST(0), (double)arg);          /* XXXXX */
  617.               }
  618.               XSRETURN(1);
  619.           }
  620.  
  621.       Notice the two lines marked with "XXXXX".  If    you check the
  622.       first    section    of the typemap file, you'll see    that doubles
  623.       are of type T_DOUBLE.     In the    INPUT section, an argument
  624.       that is T_DOUBLE is assigned to the variable arg by calling
  625.       the routine SvNV on something, then casting it to double,
  626.       then assigned    to the variable    arg.  Similarly, in the    OUTPUT
  627.       section, once    arg has    its final value, it is passed to the
  628.       sv_setnv function to be passed back to the calling
  629.       subroutine.  These two functions are explained in the
  630.       _p_e_r_l_g_u_t_s manpage; we'll talk more later about    what that
  631.       "_S_T(0)" means    in the section on the argument stack.
  632.  
  633.       WWWWAAAARRRRNNNNIIIINNNNGGGG
  634.  
  635.       In general, it's not a good idea to write extensions that
  636.       modify their input parameters, as in Example 3.  However, to
  637.       accommodate better calling pre-existing C routines, which
  638.       often    do modify their    input parameters, this behavior    is
  639.       tolerated.  The next example will show how to    do this.
  640.  
  641.       EEEEXXXXAAAAMMMMPPPPLLLLEEEE 4444
  642.  
  643.       In this example, we'll now begin to write XSUBs that will
  644.       interact with    predefined C libraries.     To begin with,    we
  645.       will build a small library of    our own, then let h2xs write
  646.       our .pm and .xs files    for us.
  647.  
  648.       Create a new directory called    Mytest2    at the same level as
  649.       the directory    Mytest.     In the    Mytest2    directory, create
  650.       another directory called mylib, and cd into that directory.
  651.  
  652.       Here we'll create some files that will generate a test
  653.       library.  These will include a C source file and a header
  654.  
  655.  
  656.  
  657.      Page 10                        (printed 10/23/98)
  658.  
  659.  
  660.  
  661.  
  662.  
  663.  
  664.      PPPPEEEERRRRLLLLXXXXSSSSTTTTUUUUTTTT((((1111))))    22223333////JJJJuuuullll////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))      PPPPEEEERRRRLLLLXXXXSSSSTTTTUUUUTTTT((((1111))))
  665.  
  666.  
  667.  
  668.       file.     We'll also create a Makefile.PL in this directory.
  669.       Then we'll make sure that running make at the    Mytest2    level
  670.       will automatically run this Makefile.PL file and the
  671.       resulting Makefile.
  672.  
  673.       In the testlib directory, create a file mylib.h that looks
  674.       like this:
  675.  
  676.           #define TESTVAL 4
  677.  
  678.           extern double      foo(int, long, const char*);
  679.  
  680.       Also create a    file mylib.c that looks    like this:
  681.  
  682.           #include <stdlib.h>
  683.           #include "./mylib.h"
  684.  
  685.           double
  686.           foo(a, b, c)
  687.           int          a;
  688.           long          b;
  689.           const    char *      c;
  690.           {
  691.               return (a + b    + atof(c) + TESTVAL);
  692.           }
  693.  
  694.       And finally create a file Makefile.PL    that looks like    this:
  695.  
  696.           use ExtUtils::MakeMaker;
  697.           $Verbose = 1;
  698.           WriteMakefile(
  699.               NAME    => 'Mytest2::mylib',
  700.               SKIP    => [qw(all static static_lib dynamic dynamic_lib)],
  701.               clean    => {'FILES' => 'libmylib$(LIB_EXT)'},
  702.           );
  703.  
  704.           sub MY::top_targets {
  705.               '
  706.           all :: static
  707.  
  708.           static ::      libmylib$(LIB_EXT)
  709.  
  710.           libmylib$(LIB_EXT): $(O_FILES)
  711.               $(AR)    cr libmylib$(LIB_EXT) $(O_FILES)
  712.               $(RANLIB) libmylib$(LIB_EXT)
  713.  
  714.           ';
  715.           }
  716.  
  717.       We will now create the main top-level    Mytest2    files.    Change
  718.       to the directory above Mytest2 and run the following
  719.       command:
  720.  
  721.  
  722.  
  723.      Page 11                        (printed 10/23/98)
  724.  
  725.  
  726.  
  727.  
  728.  
  729.  
  730.      PPPPEEEERRRRLLLLXXXXSSSSTTTTUUUUTTTT((((1111))))    22223333////JJJJuuuullll////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))      PPPPEEEERRRRLLLLXXXXSSSSTTTTUUUUTTTT((((1111))))
  731.  
  732.  
  733.  
  734.           % h2xs -O -n Mytest2 ./Mytest2/mylib/mylib.h
  735.  
  736.       This will print out a    warning    about overwriting Mytest2, but
  737.       that's okay.    Our files are stored in    Mytest2/mylib, and
  738.       will be untouched.
  739.  
  740.       The normal Makefile.PL that h2xs generates doesn't know
  741.       about    the mylib directory.  We need to tell it that there is
  742.       a subdirectory and that we will be generating    a library in
  743.       it.  Let's add the following key-value pair to the
  744.       WriteMakefile    call:
  745.  
  746.           'MYEXTLIB' =>    'mylib/libmylib$(LIB_EXT)',
  747.  
  748.       and a    new replacement    subroutine too:
  749.  
  750.           sub MY::postamble {
  751.           '
  752.           $(MYEXTLIB): mylib/Makefile
  753.               cd mylib && $(MAKE) $(PASTHRU)
  754.           ';
  755.           }
  756.  
  757.       (Note: Most makes will require that there be a tab character
  758.       that indents the line    cd mylib && $(MAKE) $(PASTHRU),
  759.       similarly for    the Makefile in    the subdirectory.)
  760.  
  761.       Let's    also fix the MANIFEST file so that it accurately
  762.       reflects the contents    of our extension.  The single line
  763.       that says "mylib" should be replaced by the following    three
  764.       lines:
  765.  
  766.           mylib/Makefile.PL
  767.           mylib/mylib.c
  768.           mylib/mylib.h
  769.  
  770.       To keep our namespace    nice and unpolluted, edit the .pm file
  771.       and change the lines setting @EXPORT to @EXPORT_OK (there
  772.       are two: one in the line beginning "use vars"    and one
  773.       setting the array itself).  Finally, in the .xs file,    edit
  774.       the #include line to read:
  775.  
  776.           #include "mylib/mylib.h"
  777.  
  778.       And also add the following function definition to the    end of
  779.       the .xs file:
  780.  
  781.  
  782.  
  783.  
  784.  
  785.  
  786.  
  787.  
  788.  
  789.      Page 12                        (printed 10/23/98)
  790.  
  791.  
  792.  
  793.  
  794.  
  795.  
  796.      PPPPEEEERRRRLLLLXXXXSSSSTTTTUUUUTTTT((((1111))))    22223333////JJJJuuuullll////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))      PPPPEEEERRRRLLLLXXXXSSSSTTTTUUUUTTTT((((1111))))
  797.  
  798.  
  799.  
  800.           double
  801.           foo(a,b,c)
  802.               int          a
  803.               long          b
  804.               const    char *      c
  805.               OUTPUT:
  806.               RETVAL
  807.  
  808.       Now we also need to create a typemap file because the
  809.       default Perl doesn't currently support the const char    *
  810.       type.     Create    a file called typemap and place    the following
  811.       in it:
  812.  
  813.           const    char *      T_PV
  814.  
  815.       Now run perl on the top-level    Makefile.PL.  Notice that it
  816.       also created a Makefile in the mylib directory.  Run make
  817.       and see that it does cd into the mylib directory and run
  818.       make in there    as well.
  819.  
  820.       Now edit the test.pl script and change the BEGIN block to
  821.       print    "1..4",    and add    the following lines to the end of the
  822.       script:
  823.  
  824.           print    &Mytest2::foo(1, 2, "Hello, world!") ==    7 ? "ok    2\n" : "not ok 2\n";
  825.           print    &Mytest2::foo(1, 2, "0.0") == 7    ? "ok 3\n" : "not ok 3\n";
  826.           print    abs(&Mytest2::foo(0, 0,    "-3.4")    - 0.6) <= 0.01 ? "ok 4\n" : "not ok 4\n";
  827.  
  828.       (When    dealing    with floating-point comparisons, it is often
  829.       useful not to    check for equality, but    rather the difference
  830.       being    below a    certain    epsilon    factor,    0.01 in    this case)
  831.  
  832.       Run "make test" and all should be well.
  833.  
  834.       WWWWHHHHAAAATTTT HHHHAAAASSSS HHHHAAAAPPPPPPPPEEEENNNNEEEEDDDD HHHHEEEERRRREEEE????
  835.  
  836.       Unlike previous examples, we've now run h2xs on a real
  837.       include file.     This has caused some extra goodies to appear
  838.       in both the .pm and .xs files.
  839.  
  840.       +o   In the .xs file, there's now a #include declaration with
  841.           the full path to the mylib.h header file.
  842.  
  843.       +o   There's now some new C code that's been added to the .xs
  844.           file.  The purpose of the    constant routine is to make
  845.           the values that are #define'd in the header file
  846.           available    to the Perl script (in this case, by calling
  847.           &main::TESTVAL).    There's    also some XS code to allow
  848.           calls to the constant routine.
  849.  
  850.       +o   The .pm file has exported    the name TESTVAL in the
  851.           @EXPORT array.  This could lead to name clashes.    A good
  852.  
  853.  
  854.  
  855.      Page 13                        (printed 10/23/98)
  856.  
  857.  
  858.  
  859.  
  860.  
  861.  
  862.      PPPPEEEERRRRLLLLXXXXSSSSTTTTUUUUTTTT((((1111))))    22223333////JJJJuuuullll////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))      PPPPEEEERRRRLLLLXXXXSSSSTTTTUUUUTTTT((((1111))))
  863.  
  864.  
  865.  
  866.           rule of thumb is that if the #define is going to be used
  867.           by only the C routines themselves, and not by the    user,
  868.           they should be removed from the @EXPORT array.
  869.           Alternately, if you don't    mind using the "fully
  870.           qualified    name" of a variable, you could remove most or
  871.           all of the items in the @EXPORT array.
  872.  
  873.       +o   If our include file contained #include directives, these
  874.           would not    be processed at    all by h2xs.  There is no good
  875.           solution to this right now.
  876.  
  877.       We've    also told Perl about the library that we built in the
  878.       mylib    subdirectory.  That required the addition of only the
  879.       MYEXTLIB variable to the WriteMakefile call and the
  880.       replacement of the postamble subroutine to cd    into the
  881.       subdirectory and run make.  The Makefile.PL for the library
  882.       is a bit more    complicated, but not excessively so.  Again we
  883.       replaced the postamble subroutine to insert our own code.
  884.       This code specified simply that the library to be created
  885.       here was a static archive (as    opposed    to a dynamically
  886.       loadable library) and    provided the commands to build it.
  887.  
  888.       SSSSPPPPEEEECCCCIIIIFFFFYYYYIIIINNNNGGGG AAAARRRRGGGGUUUUMMMMEEEENNNNTTTTSSSS TTTTOOOO XXXXSSSSUUUUBBBBPPPPPPPP
  889.  
  890.       With the completion of Example 4, we now have    an easy    way to
  891.       simulate some    real-life libraries whose interfaces may not
  892.       be the cleanest in the world.     We shall now continue with a
  893.       discussion of    the arguments passed to    the xsubpp compiler.
  894.  
  895.       When you specify arguments in    the .xs    file, you are really
  896.       passing three    pieces of information for each one listed.
  897.       The first piece is the order of that argument    relative to
  898.       the others (first, second, etc).  The    second is the type of
  899.       argument, and    consists of the    type declaration of the
  900.       argument (e.g., int, char*, etc).  The third piece is    the
  901.       exact    way in which the argument should be used in the    call
  902.       to the library function from this XSUB.  This    would mean
  903.       whether or not to place a "&"    before the argument or not,
  904.       meaning the argument expects to be passed the    address    of the
  905.       specified data type.
  906.  
  907.       There    is a difference    between    the two    arguments in this
  908.       hypothetical function:
  909.  
  910.           int
  911.           foo(a,b)
  912.               char      &a
  913.               char *  b
  914.  
  915.       The first argument to    this function would be treated as a
  916.       char and assigned to the variable a, and its address would
  917.       be passed into the function foo.  The    second argument    would
  918.  
  919.  
  920.  
  921.      Page 14                        (printed 10/23/98)
  922.  
  923.  
  924.  
  925.  
  926.  
  927.  
  928.      PPPPEEEERRRRLLLLXXXXSSSSTTTTUUUUTTTT((((1111))))    22223333////JJJJuuuullll////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))      PPPPEEEERRRRLLLLXXXXSSSSTTTTUUUUTTTT((((1111))))
  929.  
  930.  
  931.  
  932.       be treated as    a string pointer and assigned to the variable
  933.       b.  The _v_a_l_u_e    of b would be passed into the function foo.
  934.       The actual call to the function foo that xsubpp generates
  935.       would    look like this:
  936.  
  937.           foo(&a, b);
  938.  
  939.       Xsubpp will identically parse    the following function
  940.       argument lists:
  941.  
  942.           char      &a
  943.           char&a
  944.           char      & a
  945.  
  946.       However, to help ease    understanding, it is suggested that
  947.       you place a "&" next to the variable name and    away from the
  948.       variable type), and place a "*" near the variable type, but
  949.       away from the    variable name (as in the complete example
  950.       above).  By doing so,    it is easy to understand exactly what
  951.       will be passed to the    C function -- it will be whatever is
  952.       in the "last column".
  953.  
  954.       You should take great    pains to try to    pass the function the
  955.       type of variable it wants, when possible.  It    will save you
  956.       a lot    of trouble in the long run.
  957.  
  958.       TTTTHHHHEEEE AAAARRRRGGGGUUUUMMMMEEEENNNNTTTT SSSSTTTTAAAACCCCKKKK
  959.  
  960.       If we    look at    any of the C code generated by any of the
  961.       examples except example 1, you will notice a number of
  962.       references to    _S_T(n), where n is usually 0.  The "ST" is
  963.       actually a macro that    points to the n'th argument on the
  964.       argument stack.  _S_T(0) is thus the first argument passed to
  965.       the XSUB, _S_T(1) is the second    argument, and so on.
  966.  
  967.       When you list    the arguments to the XSUB in the .xs file,
  968.       that tells xsubpp which argument corresponds to which    of the
  969.       argument stack (i.e.,    the first one listed is    the first
  970.       argument, and    so on).     You invite disaster if    you do not
  971.       list them in the same    order as the function expects them.
  972.  
  973.       EEEEXXXXTTTTEEEENNNNDDDDIIIINNNNGGGG YYYYOOOOUUUURRRR EEEEXXXXTTTTEEEENNNNSSSSIIIIOOOONNNN
  974.  
  975.       Sometimes you    might want to provide some extra methods or
  976.       subroutines to assist    in making the interface    between    Perl
  977.       and your extension simpler or    easier to understand.  These
  978.       routines should live in the .pm file.     Whether they are
  979.       automatically    loaded when the    extension itself is loaded or
  980.       loaded only when called depends on where in the .pm file the
  981.       subroutine definition    is placed.
  982.  
  983.  
  984.  
  985.  
  986.  
  987.      Page 15                        (printed 10/23/98)
  988.  
  989.  
  990.  
  991.  
  992.  
  993.  
  994.      PPPPEEEERRRRLLLLXXXXSSSSTTTTUUUUTTTT((((1111))))    22223333////JJJJuuuullll////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))      PPPPEEEERRRRLLLLXXXXSSSSTTTTUUUUTTTT((((1111))))
  995.  
  996.  
  997.  
  998.       DDDDOOOOCCCCUUUUMMMMEEEENNNNTTTTIIIINNNNGGGG YYYYOOOOUUUURRRR EEEEXXXXTTTTEEEENNNNSSSSIIIIOOOONNNN
  999.  
  1000.       There    is absolutely no excuse    for not    documenting your
  1001.       extension.  Documentation belongs in the .pm file.  This
  1002.       file will be fed to pod2man, and the embedded    documentation
  1003.       will be converted to the manpage format, then    placed in the
  1004.       blib directory.  It will be copied to    Perl's man page
  1005.       directory when the extension is installed.
  1006.  
  1007.       You may intersperse documentation and    Perl code within the
  1008.       .pm file.  In    fact, if you want to use method    autoloading,
  1009.       you must do this, as the comment inside the .pm file
  1010.       explains.
  1011.  
  1012.       See the _p_e_r_l_p_o_d manpage for more information about the pod
  1013.       format.
  1014.  
  1015.       IIIINNNNSSSSTTTTAAAALLLLLLLLIIIINNNNGGGG YYYYOOOOUUUURRRR EEEEXXXXTTTTEEEENNNNSSSSIIIIOOOONNNN
  1016.  
  1017.       Once your extension is complete and passes all its tests,
  1018.       installing it    is quite simple: you simply run    "make
  1019.       install".  You will either need to have write    permission
  1020.       into the directories where Perl is installed,    or ask your
  1021.       system administrator to run the make for you.
  1022.  
  1023.       SSSSEEEEEEEE AAAALLLLSSSSOOOO
  1024.  
  1025.       For more information,    consult    the _p_e_r_l_g_u_t_s manpage, the
  1026.       _p_e_r_l_x_s manpage, the _p_e_r_l_m_o_d manpage, and the _p_e_r_l_p_o_d
  1027.       manpage.
  1028.  
  1029.       AAAAuuuutttthhhhoooorrrr
  1030.  
  1031.       Jeff Okamoto <_o_k_a_m_o_t_o@_c_o_r_p._h_p._c_o_m>
  1032.  
  1033.       Reviewed and assisted    by Dean    Roehrich, Ilya Zakharevich,
  1034.       Andreas Koenig, and Tim Bunce.
  1035.  
  1036.       LLLLaaaasssstttt CCCChhhhaaaannnnggggeeeedddd
  1037.  
  1038.       1996/7/10
  1039.  
  1040.  
  1041.  
  1042.  
  1043.  
  1044.  
  1045.  
  1046.  
  1047.  
  1048.  
  1049.  
  1050.  
  1051.  
  1052.  
  1053.      Page 16                        (printed 10/23/98)
  1054.  
  1055.  
  1056.  
  1057.  
  1058.  
  1059.  
  1060.      PPPPEEEERRRRLLLLXXXXSSSSTTTTUUUUTTTT((((1111))))    22223333////JJJJuuuullll////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))      PPPPEEEERRRRLLLLXXXXSSSSTTTTUUUUTTTT((((1111))))
  1061.  
  1062.  
  1063.  
  1064.  
  1065.  
  1066.  
  1067.  
  1068.  
  1069.  
  1070.  
  1071.  
  1072.  
  1073.  
  1074.  
  1075.  
  1076.  
  1077.  
  1078.  
  1079.  
  1080.  
  1081.  
  1082.  
  1083.  
  1084.  
  1085.  
  1086.  
  1087.  
  1088.  
  1089.  
  1090.  
  1091.  
  1092.  
  1093.  
  1094.  
  1095.  
  1096.  
  1097.  
  1098.  
  1099.  
  1100.  
  1101.  
  1102.  
  1103.  
  1104.  
  1105.  
  1106.  
  1107.  
  1108.  
  1109.  
  1110.  
  1111.  
  1112.  
  1113.  
  1114.  
  1115.  
  1116.      Page 17                        (printed 10/23/98)
  1117.  
  1118.  
  1119.  
  1120.  
  1121.  
  1122.  
  1123.